import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthTenant } from '~/modules/tenant/tenant.decorator';
import { MissionEntity } from '~/modules/mission/mission.entity';
import { AuthUser } from '~/modules/auth/decorators/auth-user.decorator';
import { Public } from '~/modules/auth/decorators/public.decorator';
import { ApiTenantHeader } from '~/common/decorators/api-header-tenant.decorator';
import { MissionRecordDto } from '~/modules/mission/mission.dto';
import { MissionService } from '~/modules/mission/mission.service';
import { PointsLogService } from '~/modules/points/points-log/points-log.service';
import { AllowAnon } from '~/modules/auth/decorators/allow-anon.decorator';
import { CountMissionModel } from '~/modules/mission/mission.model';

@ApiBearerAuth()
@ApiTags('Mission - 任务')
@Controller('mission')
export class MiniappMissionController {
  constructor(
    private readonly missionService: MissionService,
		private readonly pointsLogService: PointsLogService
  ) {}

  @Public()
  @Get()
  @ApiTenantHeader()
  @ApiOperation({ summary: '获取小程序任务' })
  async getMission(
    @AuthUser() user: IAuthUser
  ): Promise<Array<Partial<MissionEntity>>> {
    return this.missionService.findAllByTenantId(user?.uid);
  }

  @Post('record')
  @ApiOperation({ summary: '完成任务' })
  @ApiTenantHeader()
  @ApiBody({ type: MissionRecordDto })
  async finishMission(
    @Body() dto: MissionRecordDto,
    @AuthUser() user: IAuthUser
  ): Promise<void> {
    // 记录用户完成情况
    this.missionService.recordMissionFinish(user?.uid, dto);
  }

	@Public()
  @Get('self')
  @ApiOperation({ summary: '我的任务' })
  async getSelfMission(
    @AuthTenant() tenant: IAuthTenant,
    @AuthUser() user: IAuthUser
  ): Promise<{points: number, doing: Array<CountMissionModel>, done: Array<CountMissionModel>}> {
    // 返回 已经领取的积分、进行中的任务、已完成的任务
		const points = await this.pointsLogService.countByUserId(user?.uid);
		const {doing, done} = await this.missionService.getMissionByUser(user?.uid, tenant?.id)
    return {points, doing, done};
  }

	@Public()
	@Get('catalog/:categoryId')
	@ApiOperation({ summary: '获取目录分类任务的完成进度' })
	async getMissionLogByCatalogCategoryId(
		@AuthUser() user: IAuthUser,
		@Param('categoryId') categoryId: number
	): Promise<Record<string, any>> {
		return this.missionService.getMissionLogByCatalogCategoryId(user?.uid, Number(categoryId));
	}
}
